<?php
namespace app\admin\controller;
use app\admin\model\Article as ArticleModel;
use app\admin\model\Cate as CateModel;

class Article extends Base
{
    public function lst()
    {
        $article = new ArticleModel;
        $articles = $article->field('a.*,b.catename')->alias('a')->join('cate b','a.cateid=b.id')->order('a.id desc')->paginate(10);

//        $articles = db('article')->field('a.*,b.catename')->alias('a')->join('bk_cate b','a.cateid=b.id')->order('a.id desc')->paginate(10);
        $this->assign('articles',$articles);
        return view();
    }

    public function add()
    {
        if(request()->isPost()){
            $data = input('post.');
            $data['time'] = time();
            $validate = \think\Loader::validate('Article');
            if(!$validate->scene('add')->check($data)){
                $this->error($validate->getError());
            }
            $article = new ArticleModel();

            if($article->save($data)){
                $this->success('添加文章成功',url('lst'));
            }else{
                $this->error('添加文章失败！');
            }
            return;
        }
        $cate = new CateModel();
        $cateres = $cate->catetree();
        $this->assign('cateres',$cateres);
        return view();
    }

    public function edit(){
        $id = input('id');
        $article = new ArticleModel();
        if (request()->isPost()){
            $data = input('post.');
            $validate = \think\Loader::validate('Article');
            if(!$validate->scene('edit')->check($data)){
                $this->error($validate->getError());
                die;
            }
//          $data = [
//              'id'=>input('id'),
//              'title'=>input('title'),
//              'author'=>input('author'),
//              'desc'=>input('desc'),
//              'keywords'=>str_replace('，',',',input('keywords')),
//              'content'=>input('content'),
//              'cateid'=>input('cateid'),
//              'hot'=>input('hot'),
//          ];
            $data = input('post.');
            $data['keywords'] = str_replace('，',',',input('keywords'));
            $save = $article->update($data);
            if($save){
                $this->success('修改文章成功','lst');
            }else{
                $this->error('修改文章失败');
            }
            return;
        }
        $articles = $article->find($id);
        $this->assign('articles', $articles);
        $cate = new CateModel();
        $cateres = $cate->catetree();
        $this->assign('cateres', $cateres);
        return view();
    }

    public function del(){
        $id = input('id');
        if(ArticleModel::destroy($id)){
            $this->success("删除文章成功！", 'lst');
        }else{
            $this->error('删除文章失败');
        }
    }
}
